package com.saris.primego.service.impl;

import com.saris.primego.common.constant.MessageConstant;
import com.saris.primego.common.context.BaseContext;
import com.saris.primego.common.exception.ShoppingCartBusinessException;
import com.saris.primego.dao.DishRepository;
import com.saris.primego.dao.SetmealRepository;
import com.saris.primego.dao.ShoppingCartRepository;
import com.saris.primego.pojo.dto.ShoppingCartDTO;
import com.saris.primego.pojo.entity.Dish;
import com.saris.primego.pojo.entity.Setmeal;
import com.saris.primego.pojo.entity.ShoppingCart;
import com.saris.primego.service.ShoppingCartService;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
@Slf4j
public class ShoppingCartServiceImpl implements ShoppingCartService {

    private final ShoppingCartRepository shoppingCartRepository;
    private final DishRepository dishRepository;
    private final SetmealRepository setmealRepository;

    public ShoppingCartServiceImpl(ShoppingCartRepository shoppingCartRepository, DishRepository dishRepository, SetmealRepository setmealRepository) {
        this.shoppingCartRepository = shoppingCartRepository;
        this.dishRepository = dishRepository;
        this.setmealRepository = setmealRepository;
    }

    /**
     * 添加购物车
     */
    @Transactional
    public void addShoppingCart(ShoppingCartDTO shoppingCartDTO) {
        //本次添加到购物车的是菜品
        Long dishId = shoppingCartDTO.getDishId();
        Long userId = BaseContext.getCurrentId();
        String dishFlavor = shoppingCartDTO.getDishFlavor();

        if (dishId != null) {
            List<ShoppingCart> allByUserIdAndDishId = shoppingCartRepository.getAllByUserIdAndDishId(userId, dishId);
            if (!allByUserIdAndDishId.isEmpty()) { //判断当前加入到购物车中的商品是否已经存在了
                ShoppingCart dishCart = allByUserIdAndDishId.getFirst();
                dishCart.setNumber(dishCart.getNumber() + 1);//如果已经存在了，只需要将数量加一
                shoppingCartRepository.save(dishCart);
            } else {//如果不存在，需要插入一条购物车数据
                Optional<Dish> optionalDish = dishRepository.findById(dishId);
                if (optionalDish.isPresent()) {
                    Dish dish = optionalDish.get();
                    ShoppingCart shoppingCart = new ShoppingCart();
                    shoppingCart.setDishId(dishId);
                    shoppingCart.setUserId(userId);
                    if (dishFlavor != null) shoppingCart.setDishFlavor(dishFlavor);
                    shoppingCart.setName(dish.getName());
                    shoppingCart.setImage(dish.getImage());
                    shoppingCart.setAmount(dish.getPrice());
                    shoppingCart.setNumber(1);
                    shoppingCartRepository.saveAndFlush(shoppingCart);
                }
            }
        }

        //本次添加到购物车的是套餐
        Long setmealId = shoppingCartDTO.getSetmealId();
        if (setmealId != null) {
            List<ShoppingCart> allByUserIdAndSetmealId = shoppingCartRepository.getAllByUserIdAndSetmealId(userId, setmealId);
            if (!allByUserIdAndSetmealId.isEmpty()) { //判断当前加入到购物车中的商品是否已经存在了
                ShoppingCart shoppingCart = allByUserIdAndSetmealId.getFirst();
                shoppingCart.setNumber(shoppingCart.getNumber() + 1);//如果已经存在了，只需要将数量加一
                shoppingCartRepository.save(shoppingCart);
            } else {//如果不存在，需要插入一条购物车数据
                Optional<Setmeal> optionalSetmeal = setmealRepository.findById(setmealId);
                if (optionalSetmeal.isPresent()) {
                    Setmeal setmeal = optionalSetmeal.get();
                    ShoppingCart shoppingCart = new ShoppingCart();
                    shoppingCart.setSetmealId(setmealId);
                    shoppingCart.setUserId(userId);
                    if (dishFlavor != null) shoppingCart.setDishFlavor(dishFlavor);
                    shoppingCart.setName(setmeal.getName());
                    shoppingCart.setImage(setmeal.getImage());
                    shoppingCart.setAmount(setmeal.getPrice());
                    shoppingCart.setNumber(1);
                    shoppingCartRepository.save(shoppingCart);
                }
            }
        }
    }

    /**
     * 查看购物车
     */
    public List<ShoppingCart> showShoppingCart() {
        //获取到当前微信用户的id
        Long userId = BaseContext.getCurrentId();

        return shoppingCartRepository.findAllByUserId(userId).orElseThrow(()->new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL));
    }

    /**
     * 清空购物车
     */
    @Transactional
    public void cleanShoppingCart() {
        //获取到当前微信用户的id
        Long userId = BaseContext.getCurrentId();

        shoppingCartRepository.deleteByUserId(userId);
    }

    /**
     * 删除购物车中一个商品
     */
    @Transactional
    public void subShoppingCart(ShoppingCartDTO shoppingCartDTO) {
        if (shoppingCartDTO.getDishId() != null) {
            //查询当前登录用户添加菜品的购物车数据
            ShoppingCart dishCart = shoppingCartRepository.getAllByUserIdAndDishId(BaseContext.getCurrentId(), shoppingCartDTO.getDishId()).getFirst();

            if (dishCart != null) {
                Integer number = dishCart.getNumber();
                if (number> 1) {
                    //当前商品在购物车中的份数不为1，修改份数即可
                    dishCart.setNumber(number - 1);
                    shoppingCartRepository.save(dishCart);
                } else {
                    //当前商品在购物车中的份数为1，直接删除
                    shoppingCartRepository.delete(dishCart);
                }
            }
        }

        ShoppingCart shoppingCart = shoppingCartRepository.getAllByUserIdAndSetmealId(BaseContext.getCurrentId(), shoppingCartDTO.getSetmealId()).getFirst();

        if (shoppingCart != null) {
            Integer number = shoppingCart.getNumber();
            //当前商品在购物车中的份数不为1，修改份数即可
            if (number > 1) {
                shoppingCart.setNumber(number - 1);
                shoppingCartRepository.save(shoppingCart);
            }
            {
                //当前商品在购物车中的份数为1，直接删除
                shoppingCartRepository.delete(shoppingCart);
            }
        }
    }
}
